import { createSlice, type Slice } from "@reduxjs/toolkit";
import type { UserStore } from "../type/StoreType";

const userSlice: Slice<UserStore> = createSlice({
  name: 'user',
  initialState: {
    user: localStorage.user ? JSON.parse(localStorage.user) : {},
    loginRemember: localStorage.loginRemember ? JSON.parse(localStorage.loginRemember) : { remember: true },
    activeRoute: localStorage.activeRoute ? JSON.parse(localStorage.activeRoute) : { selectKey: '', openKey: '' },
    table: { page: 1, size: 10, list: [], search: {}, selectRow: [], editItem: null, refresh: false } as UserStore['table']
  },
  reducers: {
    setUser(state, action) {
      state.user = action.payload
      localStorage.user = JSON.stringify(action.payload)
    },
    setLoginRemember(state, action) {
      state.loginRemember = action.payload
      localStorage.loginRemember = JSON.stringify(action.payload)
    },
    setActiveRoute(state, action) {
      // console.log(action.payload)
      state.activeRoute = action.payload
      localStorage.activeRoute = JSON.stringify(action.payload)
    },
    setTable(state, action) {
      state.table = action.payload
    }
  }
})

export const { setUser, setLoginRemember, setActiveRoute, setTable } = userSlice.actions
export default userSlice
